package com.clb.studyproject.weights

import android.content.Context
import android.graphics.Canvas
import android.graphics.Path
import android.util.AttributeSet
import com.clb.studyproject.utils.ConversionUtils

/**
 * 自定义圆角图片
 */
class RoundCornerImageView : androidx.appcompat.widget.AppCompatImageView {

    //圆角值
    private var cornerValue: Int = 0

    constructor(context: Context) : super(context) {
        init(context)
    }

    constructor(context: Context, attributeSet: AttributeSet) : super(context, attributeSet) {
        init(context, attributeSet)
    }

    fun init(context: Context, attributeSet: AttributeSet? = null) {

    }

    /**
     * 设置圆角值
     */
    fun setRoundCorner(cornerValue: Float) {
        this.cornerValue = ConversionUtils.dp2px(context, cornerValue)
        invalidate()
    }

    override fun onDraw(canvas: Canvas?) {
        if (width > cornerValue && height > cornerValue) {
            val path = Path()
            path.moveTo(cornerValue.toFloat(), 0F);
            path.lineTo(width - cornerValue.toFloat(), 0F);
            path.quadTo(width.toFloat(), 0F, width.toFloat(), cornerValue.toFloat());
            path.lineTo(width.toFloat(), height - cornerValue.toFloat());
            path.quadTo(width.toFloat(), height.toFloat(), width - cornerValue.toFloat(), height.toFloat())
            path.lineTo(cornerValue.toFloat(), height.toFloat());
            path.quadTo(0F, height.toFloat(), 0F, height - cornerValue.toFloat());
            path.lineTo(0F, cornerValue.toFloat());
            path.quadTo(0F, 0F, cornerValue.toFloat(), 0F);
            canvas?.clipPath(path);
        }
        super.onDraw(canvas)
    }
}